<template>
  <div class="tab-bar1">
    <div class="tab-container">
      <!-- 左侧滚动按钮 -->
      <div
        v-if="showLeftScroll"
        class="scroll-btn scroll-left"
        @click="scrollLeft"
      >
        <el-icon><ArrowLeft /></el-icon>
      </div>

      <div class="tab-list" ref="tabListRef">
        <div
          v-for="tab in tabList"
          :key="tab.path"
          :class="['tab-item', { active: activeTab === tab.path }]"
          @click="handleTabClick(tab)"
          :ref="(el) => (tabRefs[tab.path] = el)"
        >
          <svg-icon :icon-class="tab.icon" class="tab-icon" />
          <span class="tab-text">{{ tab.title }}</span>
          <el-icon
            v-if="tabList.length > 1"
            class="tab-close"
            @click.stop="handleTabClose(tab)"
          >
            <Close />
          </el-icon>
        </div>
      </div>

      <!-- 右侧滚动按钮 -->
      <div
        v-if="showRightScroll"
        class="scroll-btn scroll-right"
        @click="scrollRight"
      >
        <el-icon><ArrowRight /></el-icon>
      </div>

      <!-- 右侧操作按钮 -->
      <div class="tab-actions">
        <el-dropdown @command="handleAction">
          <el-icon class="action-icon">
            <MoreFilled />
          </el-icon>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="closeOthers"
                >关闭其他</el-dropdown-item
              >
              <el-dropdown-item command="closeAll">关闭所有</el-dropdown-item>
              <el-dropdown-item command="refresh">刷新当前</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, nextTick, onMounted, onUnmounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import {
  Close,
  MoreFilled,
  ArrowLeft,
  ArrowRight,
} from "@element-plus/icons-vue";
import useAppStore from "@/store/modules/app";

const route = useRoute();
const router = useRouter();
const appStore = useAppStore();

const tabList = ref([]);
const activeTab = ref("");
const tabListRef = ref(null);
const tabRefs = ref({});
const scrollPosition = ref(0);
const showLeftScroll = ref(false);
const showRightScroll = ref(false);

// 添加页签
const addTab = (tab) => {
  const existingTab = tabList.value.find((t) => t.path === tab.path);
  if (!existingTab) {
    tabList.value.push(tab);
  }
};

// 监听路由变化，更新页签
watch(
  () => route.path,
  (newPath) => {
    activeTab.value = newPath;
    addTab({
      path: newPath,
      title: route.meta?.title || "未命名页面",
      icon: route.meta?.icon || "document",
    });
    // 确保新激活的标签在可视区域内
    nextTick(() => {
      scrollToTab(newPath);
      checkScrollStatus();
    });
  },
  { immediate: true }
);

// 页签点击
const handleTabClick = (tab) => {
  if (tab.path !== route.path) {
    router.push(tab.path);
  }
  // 确保点击的标签在可视区域内
  scrollToTab(tab.path);
};

// 关闭页签
const handleTabClose = (tab) => {
  const index = tabList.value.findIndex((t) => t.path === tab.path);
  if (index > -1) {
    tabList.value.splice(index, 1);

    // 如果关闭的是当前页签，跳转到其他页签
    if (tab.path === route.path && tabList.value.length > 0) {
      const nextTab = tabList.value[Math.min(index, tabList.value.length - 1)];
      router.push(nextTab.path);
    }
  }
};

// 检查滚动状态
const checkScrollStatus = () => {
  if (!tabListRef.value) return;

  const container = tabListRef.value;
  const containerWidth = container.clientWidth;
  const scrollWidth = container.scrollWidth;

  showLeftScroll.value = scrollPosition.value > 0;
  showRightScroll.value = scrollPosition.value < scrollWidth - containerWidth;
};

// 滚动到左侧
const scrollLeft = () => {
  if (!tabListRef.value) return;

  const container = tabListRef.value;
  const scrollAmount = 200;
  const newScrollLeft = Math.max(0, scrollPosition.value - scrollAmount);

  container.scrollTo({
    left: newScrollLeft,
    behavior: "smooth",
  });
};

// 滚动到右侧
const scrollRight = () => {
  if (!tabListRef.value) return;

  const container = tabListRef.value;
  const scrollAmount = 200;
  const maxScrollLeft = container.scrollWidth - container.clientWidth;
  const newScrollLeft = Math.min(
    maxScrollLeft,
    scrollPosition.value + scrollAmount
  );

  container.scrollTo({
    left: newScrollLeft,
    behavior: "smooth",
  });
};

// 滚动到指定标签
const scrollToTab = (tabPath) => {
  nextTick(() => {
    const tabElement = tabRefs.value[tabPath];
    if (!tabElement || !tabListRef.value) return;

    const container = tabListRef.value;
    const tabRect = tabElement.getBoundingClientRect();
    const containerRect = container.getBoundingClientRect();

    // 如果标签在可视区域外，滚动到标签位置
    if (tabRect.left < containerRect.left) {
      // 标签在左侧，滚动到标签开始位置
      container.scrollTo({
        left: scrollPosition.value + (tabRect.left - containerRect.left),
        behavior: "smooth",
      });
    } else if (tabRect.right > containerRect.right) {
      // 标签在右侧，滚动到标签结束位置
      container.scrollTo({
        left: scrollPosition.value + (tabRect.right - containerRect.right),
        behavior: "smooth",
      });
    }
  });
};

// 监听滚动事件
const handleScroll = () => {
  if (!tabListRef.value) return;
  scrollPosition.value = tabListRef.value.scrollLeft;
  checkScrollStatus();
};

// 操作处理
const handleAction = (command) => {
  switch (command) {
    case "closeOthers":
      tabList.value = tabList.value.filter((tab) => tab.path === route.path);
      break;
    case "closeAll":
      tabList.value = [];
      router.push("/dashboard"); // 跳转到综合看板页面
      break;
    case "refresh":
      // 刷新当前页面
      window.location.reload();
      break;
  }
};

// 监听窗口大小变化
const handleResize = () => {
  checkScrollStatus();
};

onMounted(() => {
  if (tabListRef.value) {
    tabListRef.value.addEventListener("scroll", handleScroll);
  }
  window.addEventListener("resize", handleResize);
  nextTick(() => {
    checkScrollStatus();
  });
});

onUnmounted(() => {
  if (tabListRef.value) {
    tabListRef.value.removeEventListener("scroll", handleScroll);
  }
  window.removeEventListener("resize", handleResize);
});
</script>

<style lang="scss" scoped>
.tab-bar1 {
  height: 40px;
  background: #fff;
  border-bottom: 1px solid #e4e7ed;
  width: 100%;
}

.tab-container {
  height: 100%;
  display: flex;
  align-items: center;
  position: relative;
}

.tab-list {
  flex: 1;
  display: flex;
  gap: 4px;
  overflow-x: auto;
  scrollbar-width: none;
  -ms-overflow-style: none;
  padding: 0 8px;

  &::-webkit-scrollbar {
    display: none;
  }
}

.scroll-btn {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  width: 24px;
  height: 24px;
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  z-index: 10;
  transition: all 0.3s;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

  &:hover {
    background: #f5f7fa;
    border-color: #16a5b7;
    color: #16a5b7;
  }

  &.scroll-left {
    left: 0;
  }

  &.scroll-right {
    right: 60px; /* 为右侧操作按钮留出空间 */
  }

  .el-icon {
    font-size: 12px;
    color: #606266;
  }
}

.tab-item {
  display: flex;
  align-items: center;
  padding: 6px 12px;
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 4px 4px 0 0;
  cursor: pointer;
  transition: all 0.3s;
  white-space: nowrap;
  min-width: 120px;
  max-width: 250px;
  position: relative;
  flex-shrink: 0;

  &:hover {
    background: #f5f7fa;
    border-color: #c0c4cc;
  }

  &.active {
    background: #16a5b7;
    border-color: #16a5b7;
    color: #fff;
    box-shadow: 0 -2px 8px rgba(22, 165, 183, 0.2);

    .tab-icon,
    .tab-text {
      color: #fff;
    }

    .tab-close {
      color: #fff;
    }
  }

  .tab-icon {
    margin-right: 4px;
    font-size: 14px;
    color: #606266;
    transition: color 0.3s;
    flex-shrink: 0; /* 防止图标被压缩 */
  }

  .tab-text {
    font-size: 13px;
    color: #606266;
    transition: color 0.3s;
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    min-width: 0; /* 允许flex项目收缩到内容宽度以下 */
  }

  .tab-close {
    margin-left: 4px;
    font-size: 12px;
    color: #c0c4cc;
    transition: color 0.3s;
    padding: 2px;
    border-radius: 2px;
    cursor: pointer;
    z-index: 10;
    position: relative;
    flex-shrink: 0; /* 防止关闭按钮被压缩 */

    &:hover {
      background: rgba(0, 0, 0, 0.1);
      color: #909399;
    }
  }
}

.tab-actions {
  margin-left: 12px;
  display: flex;
  align-items: center;
}

.action-icon {
  font-size: 16px;
  color: #606266;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  transition: all 0.3s;

  &:hover {
    background: #e4e7ed;
    color: #16a5b7;
  }
}
</style>
